package com.example.wendao.view.ui.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.example.wendao.App;
import com.example.wendao.R;
import com.example.wendao.common.ImgUtils;
import com.example.wendao.model.entity.Forum;
import com.example.wendao.model.entity.ForumPics;
import com.example.wendao.model.entity.News;
import com.example.wendao.model.entity.NewsPics;
import com.example.wendao.view.adapter.ImagePickerAdapter;
import com.example.wendao.view.utils.BitmapUtils;
import com.example.wendao.view.widget.SelectDialog;
import com.example.wendao.viewmodel.ForumViewModel;
import com.example.wendao.viewmodel.NewsViewModel;
import com.example.wendao.viewmodel.UserViewModel;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class Publish_forumFragment extends Fragment  implements ImagePickerAdapter.OnRecyclerViewItemClickListener {

    //返回发布页
    public Button forum_back_to_publish;

    //论坛标签
    public Button choose_select_tag;//选择标签
    public ConstraintLayout select_tag;//选择块布局
    public int sel_tag;////提交论坛类型
    public String tag;
    public boolean sel=false;

    public Button choose_write_tag;//自拟标签
    public ConstraintLayout write_tag;//自拟块布局
    public EditText talk_wirte_tag;//自拟标签部分
    public boolean wrt_tag;//标记是否为空
    public boolean wrt=false;//是否选择自拟

    public ConstraintLayout point;//提示选择按钮


    public RadioGroup select;
    private RadioButton food;
    private RadioButton fashion;
    private RadioButton interesting;
    private RadioButton music;
    private RadioButton sport;


    //添加照片
    public RecyclerView add_news;
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;

    private ImagePickerAdapter adapter;
    private ArrayList<ImageItem> selImageList; // 当前选择的所有图片
    private int maxImgCount = 3;               // 允许选择图片最大数

    // 图片的字节数组类别
    private List<byte[]> imgList;

    //论坛内容
    public EditText forum;
    //判断论坛内容是否为空
    public boolean context_check;
    //提交新闻
    public Button forum_publish;
    //news对象
    public Forum forum_obj;
    public ForumViewModel forumViewModel;
    private UserViewModel userViewModel;

    public Publish_forumFragment() {
        // Required empty public constructor
    }

    public static Publish_forumFragment newInstance(String param1, String param2) {
        Publish_forumFragment fragment = new Publish_forumFragment();
        Bundle args = new Bundle();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_publish_forum, container, false);
        forum_back_to_publish = view.findViewById(R.id.forum_back_to_publish);
        choose_select_tag = view.findViewById(R.id.choose_select_tag);
        choose_write_tag = view.findViewById(R.id.choose_write_tag);
        select_tag = view.findViewById(R.id.select_tag);
        write_tag = view.findViewById(R.id.write_tag);
        food = view.findViewById(R.id.food);
        fashion = view.findViewById(R.id.fashion);
        interesting = view.findViewById(R.id.interesting);
        music = view.findViewById(R.id.music);
        sport = view.findViewById(R.id.sport);
        point = view.findViewById(R.id.point);
        select = view.findViewById(R.id.forum_select);
        talk_wirte_tag = view.findViewById(R.id.talk_wirte_tag);
        forum = view.findViewById(R.id.forum);
        forum_publish = view.findViewById(R.id.forum_publish);
        forum_obj = new Forum();
        forumViewModel = new ViewModelProvider(App.getInstance()).get(ForumViewModel.class);
        userViewModel = new ViewModelProvider(App.getInstance()).get(UserViewModel.class);
        initWidget(view);

        forum_back_to_publish.setOnClickListener(view1 -> Navigation.findNavController(view1).navigate(R.id.action_publish_forumFragment_to_fragment_publish));

        choose_select_tag.setOnClickListener(view12 -> {
            //设置点击时显示选择标签块，隐藏自拟标签块
            write_tag.setVisibility(View.INVISIBLE);
            select_tag.setVisibility(View.VISIBLE);
            point.setVisibility(View.INVISIBLE);
            sel = true;//选择了选择标签
            wrt = false;
        });
        choose_write_tag.setOnClickListener(view13 -> {
            wrt = true;//选择了自拟
            sel = false;
            write_tag.setVisibility(View.VISIBLE);
            select_tag.setVisibility(View.INVISIBLE);
            point.setVisibility(View.INVISIBLE);
        });


        forum_publish.setOnClickListener(view14 -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle("提交提示");
            builder.setMessage("确认提交论坛");
            //点击确认进行信息的查验
            builder.setPositiveButton("确定", (dialog, which) -> {
                //检查是否选择按钮
                if (!sel && !wrt) {
                    Toast.makeText(getActivity(), getResources().getString(R.string.no_tag), Toast.LENGTH_SHORT).show();
                }
                else if (sel) {
                    sel_tag = 0;
                    if (select.getCheckedRadioButtonId() == R.id.food) {
                        sel_tag = 1;//选择了美食
                        tag = "#美食";
                    } else if (select.getCheckedRadioButtonId() == R.id.fashion) {
                        sel_tag = 2;//选择了时尚
                        tag = "#时尚";
                    } else if (select.getCheckedRadioButtonId() == R.id.interesting) {
                        sel_tag = 3;//选择了趣事
                        tag = "#趣事";
                    }  else if (select.getCheckedRadioButtonId() == R.id.music) {
                        sel_tag = 4;//选择了音乐
                        tag = "#音乐";
                    } else if (select.getCheckedRadioButtonId() == R.id.sport) {
                        sel_tag = 5;//选择了健身
                        tag = "#健身";
                    }
                }
                //选择了自拟
                else if (wrt) {
                    wrt_tag = false;//是否为空
                    if (talk_wirte_tag.getText().toString().trim().equals("")) {
                        wrt_tag = false;
                    } else {
                        wrt_tag = true;
                        sel_tag = 6;
                    }
                }

                //判断论坛内容是否为空
                context_check = false;
                if (forum.getText().toString().trim().equals("")) {
                    Toast.makeText(getActivity(), getResources().getString(R.string.no_content), Toast.LENGTH_SHORT).show();
                    context_check = false;
                } else context_check = true;

                if (sel_tag != 0 || wrt_tag) {

                    if (context_check)
                    {
                        if (sel_tag != 0 && !wrt_tag)//选择标签的上传
                        {
                            forum_obj.setForumTitle(tag);
                            forum_obj.setForumContent(forum.getText().toString().trim());
                            forum_obj.setForumAuthorId(userViewModel.getCurrentUser().getUserId());
                            forum_obj.setForumTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                            forum_obj.setForumTagId(sel_tag - 1);
                            // 添加论坛
                            forumViewModel.addForum(forum_obj);
                            // 上传论坛图片操作
                            uploadImage(selImageList);
                            if (imgList != null){
                                List<ForumPics> forumPicsList = new ArrayList<>();
                                for (byte[] bs : imgList){
                                    ForumPics forumPics = new ForumPics();
                                    forumPics.setForumPic(bs);
                                    forumPics.setForumPicFatherId(forumViewModel.getLatestForum().getForumId());
                                    forumPicsList.add(forumPics);
                                }
                                ForumPics[] forumPicsArray = new ForumPics[forumPicsList.size()];
                                forumViewModel.addForumPic(forumPicsList.toArray(forumPicsArray));
                            }
                            AlertDialog.Builder builder1 = new AlertDialog.Builder(getActivity());
                            builder1.setTitle("亲爱的闻道道友：");
                            builder1.setMessage("恭喜您已经发布成功啦，快去看看吧！");
                            builder1.setPositiveButton("确定", (dialogInterface, i) -> Navigation.findNavController(view).navigate(R.id.action_publish_forumFragment_to_fragment_talk_content));
                            AlertDialog alertDialog1 = builder1.create();
                            alertDialog1.show();
                        }
                        else {
                            forum_obj.setForumTitle(talk_wirte_tag.getText().toString().trim());
                            forum_obj.setForumContent(forum.getText().toString().trim());
                            forum_obj.setForumAuthorId(userViewModel.getCurrentUser().getUserId());
                            forum_obj.setForumTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                            forum_obj.setForumTagId(sel_tag - 1);
                            //还差一个图片上传
                            forumViewModel.addForum(forum_obj);
                            // 上传论坛图片操作
                            uploadImage(selImageList);
                            if (imgList != null){
                                List<ForumPics> forumPicsList = new ArrayList<>();
                                for (byte[] bs : imgList){
                                    NewsPics newsPics = new NewsPics();
                                    newsPics.setNewsPic(bs);
                                    newsPics.setNewsPicFatherId(forumViewModel.getLatestForum().getForumId());
                                }
                                ForumPics[] forumPicsArray = new ForumPics[forumPicsList.size()];
                                forumViewModel.addForumPic(forumPicsList.toArray(forumPicsArray));
                            }

                            AlertDialog.Builder builder2 = new AlertDialog.Builder(getActivity());
                            builder2.setTitle("亲爱的闻道道友：");
                            builder2.setMessage("恭喜您已经发布成功啦，快去看看吧！");
                            builder2.setPositiveButton("确定", (dialogInterface, i) -> Navigation.findNavController(view).navigate(R.id.action_publish_forumFragment_to_fragment_talk_content));
                            AlertDialog alertDialog2 = builder2.create();
                            alertDialog2.show();
                        }
                    }
                }
            });
            //点击取消
            builder.setNegativeButton("取消", (dialog, which) -> Toast.makeText(getActivity(), getResources().getString(R.string.cancle_publish), Toast.LENGTH_SHORT).show());
            builder.setNeutralButton("关闭窗口", (dialog, which) -> Toast.makeText(getActivity(), getResources().getString(R.string.cancle_publish), Toast.LENGTH_SHORT).show());
            builder.show();
        });
        return view;
    }

    private void initWidget(View view) {
        RecyclerView recyclerView = view.findViewById(R.id.add_news);
        selImageList = new ArrayList<>();
        adapter = new ImagePickerAdapter(view.getContext(), selImageList, maxImgCount);
        adapter.setOnItemClickListener(this);
        recyclerView.setLayoutManager(new GridLayoutManager(view.getContext(), 4));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);
    }

    private SelectDialog showDialog(SelectDialog.SelectDialogListener listener, List<String> names) {
        SelectDialog dialog = new SelectDialog(this.getActivity(), R.style.transparentFrameWindowStyle, listener, names);
        if (!this.getActivity().isFinishing()) {
            dialog.show();
        }
        return dialog;
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                List<String> names = new ArrayList<>();
                names.add("拍照");
                names.add("相册");
                showDialog((parent, view1, position1, id) -> {
                    switch (position1) {
                        case 0: // 直接调起相机
                            //打开选择,本次允许选择的数量
                            ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                            Intent intent = new Intent(this.getActivity(), ImageGridActivity.class);
                            intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS,true); // 是否是直接打开相机
                            startActivityForResult(intent, REQUEST_CODE_SELECT);
                            break;
                        case 1:
                            //打开选择,本次允许选择的数量
                            ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                            Intent intent1 = new Intent(this.getActivity(), ImageGridActivity.class);
                            startActivityForResult(intent1, REQUEST_CODE_SELECT);
                            break;
                        default:
                            break;
                    }
                }, names);
                break;
            default:
                Intent intentPreview = new Intent(this.getActivity(), ImagePreviewDelActivity.class);
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS,true);
                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            // 添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data
                        .getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null){
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                }
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data
                        .getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null){
                    selImageList.clear();
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                }
            }
        }
    }

    /**
     * 上传图片
     * @param pathList 要上传的图片列表
     */
    private void uploadImage(ArrayList<ImageItem> pathList) {
        Map<Integer, String> files = new HashMap<>();
        for (int i = 0; i < pathList.size(); i++) {
            String newPath = BitmapUtils
                    .compressImageUpload(pathList.get(i).path); // 保存到临时文件夹
            files.put(i, newPath);
        }
        imgList = ImgUtils.getBaosBytePathMap(files);
    }
}

